package array;

/**
 * @Classname : MoveZeroes
 * @Description : 283. 移动零
 * https://leetcode.cn/problems/move-zeroes/
 * @Author : cty
 * @Date 2023/4/5 23:15
 */


public class MoveZeroes {
    // 方法一：复制数组
    public void moveZeroes(int[] nums) {
        int n = nums.length;
        int[] tmp = new int[n];
        for (int i = 0; i < n; i++) {
            tmp[i] = nums[i];
            nums[i] = 0;
        }

        int index = 0;
        for (int i = 0; i < n; i++) {
            if (tmp[i] != 0) nums[index++] = tmp[i];
        }
    }

    // 方法二：原地对数组操作
    public void moveZeroes2(int[] nums) {
        int n = nums.length;
        // 从右向左遍历数组
        for (int i = n - 1; i >= 0; i--) {
            if (nums[i] == 0) {
                // 将0右边的数组向左平移一位，直至到达右边界或遇到0
                int j = i + 1;
                while (j < n && nums[j] != 0) {
                    nums[j - 1] = nums[j];
                    j++;
                }
                nums[j - 1] = 0;
            }
        }
    }

}
